var eb;
var quiz;


window.onload = function init() {
  eb = new EventBus(window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/eventbus');

  eb.onopen = function () {

    // Get the static data
    eb.send('vtoons.listImages', {"category": get("category")}, function (err, reply) {
      if (err) {
        console.error('Failed to retrieve images: ' + err);
        return;
      }
      quiz = new Quiz(reply.body);
      quiz.start();
    });
  };

  eb.onclose = function () {
    eb = null;
  };

  document.getElementById("prev-btn").addEventListener("click", function () {
    quiz.showPrevImage();
  });
  document.getElementById("next-btn").addEventListener("click", function () {
    quiz.showNextImage();
  });
};

function get(name) {
    if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search))
        return decodeURIComponent(name[1]);
}

function Quiz(images) {
  var that = this;
  this.currentQuestion = undefined;
  this.questions = [];
  for (var i = 0; i < images.length; i++) {
    this.questions.push(new ImageQuestion(images[i]));
  }

  this.start = function () {
    showQuestion(this.questions[0]);
  };

  function showQuestion(question) {
    that.currentQuestion = question;
    var imageSection = document.getElementById("image-section");
    if (imageSection.children.length > 0) {
      imageSection.replaceChild(question.getView(), imageSection.children[0]);
    } else {
      imageSection.appendChild(question.getView());
    }

    var responseSection = document.getElementById("response-section");
    if (responseSection.children.length > 0) {
      responseSection.replaceChild(question.response.getView(), responseSection.children[0]);
    } else {
      responseSection.appendChild(question.response.getView());
    }
  }

  this.showPrevImage = function () {
    var currentQuestionIndex = this.questions.indexOf(this.currentQuestion);
    if (currentQuestionIndex > 0) {
      currentQuestionIndex--;
      showQuestion(this.questions[currentQuestionIndex]);
    }
  };

  this.showNextImage = function () {
    var currentQuestionIndex = this.questions.indexOf(this.currentQuestion);
    if (this.currentQuestion.response.validate()) {
      if (currentQuestionIndex < this.questions.length - 1) {
        currentQuestionIndex++;
        showQuestion(this.questions[currentQuestionIndex]);
      }
    }
  };
}

function ImageQuestion(image) {
  this.response = new Response(image.imageText);

  this.getView = function () {
    var img = document.createElement("img");
    img.setAttribute("src", "");

    var downloadingImage = new Image();
    downloadingImage.onload = function () {
      img.setAttribute("src", image.imageSrc);
    };
    downloadingImage.src = image.imageSrc;

    var imageBlock = document.createElement("div");
    imageBlock.setAttribute("class", "image-block");
    imageBlock.appendChild(img);
    return imageBlock;
  }
}

function Response(text) {
  var that = this;
  this.text = text;

  this.validate = function () {
    if (that.view === undefined) {
      that.view = createView();
    }
    var valid = true;
    for (var i = 0; i < that.text.length; i++) {
      if (that.view.children[i].value.toUpperCase() !== that.text[i].toUpperCase()) {
        that.view.children[i].setAttribute("class", "letter wrong");
        valid = false;
      } else {
        that.view.children[i].setAttribute("class", "letter correct");
      }
    }
    return valid;
  };

  this.getView = function () {
    if (that.view === undefined) {
      that.view = createView();
    }
    return that.view;
  };

  function createView() {
    function switchToNextLetter(nextLetter) {
      return function (evt) {
        nextLetter.selectionStart = 0;
        nextLetter.focus();
      }
    }

    function replaceValue(evt) {
      if (evt.target.selectionStart === 0 && /[\w\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]/.test(String.fromCharCode(evt.keyCode))) {
        evt.target = '';
      }
    }

    function removeValue(prevLetter) {
      return function (evt) {
        if (evt.keyCode === 8 && evt.target.selectionStart === 0) {
          prevLetter.value = '';
          prevLetter.selectionStart = 0;
          prevLetter.focus();
        }
      }
    }


    this.view = document.createElement("div");
    this.view.setAttribute("class", "response-block");
    var previousLetterInput = undefined;
    var letterInput = undefined;
    for (var i = 0; i < text.length; i++) {
      previousLetterInput = letterInput;
      letterInput = document.createElement("input");
      letterInput.setAttribute("type", "text");
      letterInput.setAttribute("class", "letter");
      letterInput.setAttribute("size", "1");
      letterInput.setAttribute("maxLength", "1");
      if (previousLetterInput !== undefined) {
        previousLetterInput.addEventListener("input", switchToNextLetter(letterInput));
        letterInput.addEventListener("keypress", removeValue(previousLetterInput));
      }

      letterInput.addEventListener("keypress", replaceValue);
      letterInput.addEventListener("input", that.validate);
      letterInput.setAttribute("required", "true");
      this.view.appendChild(letterInput);
    }
    return this.view;
  }
}